package com.sunxiansheng.trace;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Description: traceId过滤器
 * @Author sun
 * @Create 2024/8/2 12:11
 * @Version 1.0
 */
@Component
@Slf4j
public class TraceIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        // 从请求头中获取traceId
        String traceId = httpServletRequest.getHeader(TraceIdConstant.TRACE_ID);
        // 如果请求头中没有traceId则生成一个
        if (StringUtils.isBlank(traceId)) {
            traceId = TraceIdContext.generateTraceId();
        }
        // 设置traceId到上下文中
        TraceIdContext.setTraceId(traceId);
        filterChain.doFilter(servletRequest, servletResponse);
        TraceIdContext.clearTraceId();
    }

}